package com.yilee.idouban.authorize;

import java.util.Hashtable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.yilee.idouban.R;
import com.yilee.idouban.util.AnalyzeResponse;

@SuppressLint("SetJavaScriptEnabled")
public class WebViewActivity extends Activity {

	private WebView wv;
	private ProgressBar pb;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web_view);

		wv = (WebView) findViewById(R.id.web_authorize);
		pb = (ProgressBar) findViewById(R.id.web_process);

		wv.setVisibility(View.INVISIBLE);
		pb.setVisibility(View.VISIBLE);

		WebSettings webSettings = wv.getSettings();
		webSettings.setJavaScriptEnabled(true);
		wv.requestFocus();
		Intent i = this.getIntent();
		if (!i.equals(null)) {
			Bundle b = i.getExtras();
			if (b != null) {
				if (b.containsKey("url")) {
					String url = b.getString("url");
					wv.loadUrl(url);
					wv.setWebChromeClient(new WebChromeClient() {
						public void onProgressChanged(WebView view, int progress) {
							setTitle("授权页面加载中..." + progress + "%");
							setProgress(progress * 100);
							if (progress == 100) {
								setTitle(R.string.app_name);
								wv.setVisibility(View.VISIBLE);
								pb.setVisibility(View.INVISIBLE);
							}
						}
					});
					wv.setWebViewClient(new WebViewClient() {
						@Override
						public void onPageStarted(WebView view, String url,
								Bitmap favicon) {
							// 拦截回调地址
							// TODO
							// 应写在配置文件中
							if (url.startsWith("http://yilee.info")) {
								Intent intent = new Intent(
										WebViewActivity.this,
										AuthorizeActivity.class);
								Hashtable<String, String> ht = AnalyzeResponse
										.AnalyzeAuthorizeReponse(url);
								String result = ht.get("result");
								intent.putExtra("result", result);
								if (result.equals("0")) {
									intent.putExtra("error", ht.get("error"));
								} else {
									intent.putExtra("access_token",
											ht.get("access_token"));
								}
								startActivity(intent);
								finish();
							} else {
								super.onPageStarted(view, url, favicon);
							}
						}
					});
				}
			}
		}
	}
}
